package com.manli.api.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.manli.api.base.annotation.Permissions;
import com.manli.api.dto.User;
import com.manli.api.dto.UserLinkUnionid;
import com.manli.api.enums.ResultEnums;
import com.manli.api.pojo.QueryParamsWechatAuth;
import com.manli.api.pojo.Result;
import com.manli.api.pojo.SessionInfo;
import com.manli.api.service.LoginService;
import com.manli.api.service.UserLinkUnionidService;
import com.manli.api.service.UserPermissionService;
import com.manli.api.service.UserService;
import com.manli.api.util.ResultUtil;
import com.manli.api.util.WeChatConfigUtil;
import com.manli.common.utils.HttpUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@Api(tags = "微信开放平台模块")
@RequestMapping("api/wechatopen")
public class WechatOpenController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserLinkUnionidService userLinkUnionidService;

    @Autowired
    UserService userService;

    @Autowired
    LoginService loginService;

    @Autowired
    UserPermissionService userPermissionService;

    @RequestMapping("/getUserLoginByScanQrcode")
    @ApiOperation(value = "用户扫码登陆获取code",notes = "")
    @Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
    public @ResponseBody
    Result getUserLoginByScanQrcode(HttpServletRequest request, HttpServletResponse response, @RequestBody QueryParamsWechatAuth wechatAuth) throws Exception {
        String weixinScanLoginGetAccessTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        String url=weixinScanLoginGetAccessTokenUrl.replace("APPID", "wx1cf065e04942c3a5").replace("SECRET", "168e58d8761e6d2e846378b63229757e").replace("CODE", wechatAuth.getCode());
        JSONObject data = JSONObject.parseObject(HttpUtil.httpsGet(url));
        logger.info(data.toJSONString());
        if (data.containsKey("errcode")){
            return ResultUtil.error(Integer.valueOf(data.get("errcode").toString()),data.get("errmsg").toString());
        }
        if(!data.containsKey("unionid")) {//未关注
            return ResultUtil.error(ResultEnums.USE_NOT_SUBCREIP_WECHAT.getCode(),ResultEnums.USE_NOT_SUBCREIP_WECHAT.getMsg());
        }
        //通过unionId查询是否绑定后台账号
        List<UserLinkUnionid> userLinkUnionids =  userLinkUnionidService.getByUnionid(data.get("unionid").toString() ,1);
        if(userLinkUnionids.size() == 1){
            UserLinkUnionid userLinkUnionid = userLinkUnionids.get(0);
            //获取user信息
            User user = userPermissionService.getUserByUserId(userLinkUnionid.getUserId());
            SessionInfo sessionInfo = loginService.userInfoCovertToSessionInfo(user);
            JSONObject object = loginService.getAuthToken(sessionInfo);
            return ResultUtil.success(object);
        }else if(userLinkUnionids.size() > 1){
            return ResultUtil.error(ResultEnums.TOO_MANY_LOGIN_ERR_LOGIN_Info.getCode(), ResultEnums.TOO_MANY_LOGIN_ERR_LOGIN_Info.getMsg());
        }
        return ResultUtil.success();
    }
}
